// 后端代理API服务
const BACKEND_API_URL = 'http://localhost:5000/api/ai'

export interface QwenMessage {
  role: 'user' | 'assistant' | 'system'
  content: string
}

export interface QwenResponse {
  output: {
    text: string
  }
  usage: {
    input_tokens: number
    output_tokens: number
    total_tokens: number
  }
  request_id: string
}

export interface QwenError {
  code: string
  message: string
  request_id: string
}

// 调用后端代理API
export const callQwenAPI = async (messages: QwenMessage[]): Promise<string> => {
  try {
    console.log('调用后端代理API...', { messages })
    
    const response = await fetch(`${BACKEND_API_URL}/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ messages })
    })

    console.log('后端API响应状态:', response.status, response.statusText)

    if (!response.ok) {
      const errorData = await response.json()
      console.error('后端API错误:', errorData)
      throw new Error(errorData.error || `HTTP错误: ${response.status} ${response.statusText}`)
    }

    const data = await response.json()
    console.log('后端API响应数据:', data)
    
    if (!data.success || !data.data?.message) {
      console.error('后端API返回数据格式错误:', data)
      throw new Error('API返回数据格式错误')
    }

    return data.data.message
  } catch (error) {
    console.error('后端API调用错误:', error)
    throw error
  }
}

// 测试后端连接
export const testBackendConnection = async (): Promise<boolean> => {
  try {
    console.log('测试后端连接...')
    
    const response = await fetch(`${BACKEND_API_URL}/test`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`后端连接失败: ${response.status} ${response.statusText}`)
    }

    const data = await response.json()
    console.log('后端测试响应:', data)
    
    return data.success === true
  } catch (error) {
    console.error('后端连接测试失败:', error)
    return false
  }
}

// 处理各种话题的智能引导
export const processFitnessQuery = (query: string): string => {
  const lowerQuery = query.toLowerCase()
  
  // 检测是否是问候语
  if (lowerQuery.includes('你好') || lowerQuery.includes('hi') || lowerQuery.includes('hello')) {
    return '嘿兄弟！我是小健 😎 你的直球AI朋友！不废话，直接说：不管啥问题，我都能给你最直接、最搞笑的建议！'
  }
  
  // 检测是否是工作相关
  if (lowerQuery.includes('工作') || lowerQuery.includes('职场') || lowerQuery.includes('同事') || lowerQuery.includes('老板')) {
    return '职场话题？兄弟，我直接说：职场就是战场！💼 告诉我具体啥情况，我保证给你最犀利的建议！'
  }
  
  // 检测是否是情感相关
  if (lowerQuery.includes('感情') || lowerQuery.includes('恋爱') || lowerQuery.includes('分手') || lowerQuery.includes('喜欢')) {
    return '情感问题？姐妹，这个我擅长！💕 别指望我说鸡汤，我会用最直接的方式帮你分析！'
  }
  
  // 检测是否是学习相关
  if (lowerQuery.includes('学习') || lowerQuery.includes('考试') || lowerQuery.includes('读书') || lowerQuery.includes('知识')) {
    return '学习话题？老铁，我直接说：学习有套路！📚 告诉我你卡在哪了，我保证给你最实用的方法！'
  }
  
  // 检测是否是健身相关
  if (lowerQuery.includes('健身') || lowerQuery.includes('锻炼') || lowerQuery.includes('运动') || lowerQuery.includes('减肥')) {
    return '健身话题？兄弟，我的老本行！💪 别听那些花里胡哨的，我直接告诉你什么有用！'
  }
  
  // 检测是否是抱怨或消极情绪
  if (lowerQuery.includes('累') || lowerQuery.includes('难') || lowerQuery.includes('烦') || lowerQuery.includes('压力')) {
    return '听起来你需要一些"毒舌"治愈！😏 兄弟，别矫情了，直接说啥问题，我保证让你笑出声！'
  }
  
  return query
}
